<?php

use Sdk\lib\Format;

class NewApp extends Controller {

	public function run() {
		if (!empty($_POST['pluginId']) && !empty($_POST['verId'])) {
			$_POST['pluginId'] = ucfirst($_POST['pluginId']);
			if (!Format::checkAppId($_POST['pluginId'])) {
				$this->template('message', array('message' => '应用ID格式错误'));
			}
			if (!Format::checkBranchId($_POST['verId'])) {
				$this->template('message', array('message' => '分支ID格式错误'));
			}

			try {
				Lib\Dev::AddApp($_POST['pluginId'], $_POST['verId']);
			} catch (Exception $e) {
				$this->template('message', array('message' => '应用添加失败<br />' . $e->getMessage()));
			}

			$appRoot = ROOT_PATH . '/www/' . $_POST['pluginId'] . '/' . $_POST['verId'];
			$this->_copy(ROOT_PATH . '/sdk/page/tpl', $appRoot, array(
				'{API_URI}' => '{api_uri /' . $_POST['pluginId'] . '/' . $_POST['verId'] . '/}',
				'{API_STATIC_URI}' => '{api_static_uri /' . $_POST['pluginId'] . '/' . $_POST['verId'] . '}',
			));

			$this->template('message', array('message' => '应用已在 WitFrame 中创建，请登录“<a href="https://dev.witframe.com" target="_blank">开放平台</a>”补充应用的信息<br>
				同时，本地应用目录及模板范例文件已创建，您可以开始开发了'));
		}
		$this->template('newApp', array());
	}

	private function _copy($src, $dst, $replace) {
		$dir = opendir($src);
		Shell::mkDir($dst);
		while (false !== ($file = readdir($dir))) {
			if (($file != '.') && ($file != '..')) {
				if (is_dir($src . '/' . $file)) {
					$this->_copy($src . '/' . $file, $dst . '/' . $file, $replace);
					continue;
				} else {
					$data = file_get_contents($src . '/' . $file);
					$data = str_replace(array_keys($replace), array_values($replace), $data);
					file_put_contents($dst . '/' . $file, $data);
				}
			}
		}
		closedir($dir);
	}

}